<template>
  <div class="">
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl"  />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";

export default {
  components: {},
  data() {
    return {
      imageUrl: "",
    };
  },
  methods: {
    // 文件上传成功后
    handleAvatarSuccess: function (res) {
      let imageUrl = "http://linweiqin.cn:8001/img/" + res.image_path;
      this.imageUrl = imageUrl;
    },
    //上传之前校验
    beforeAvatarUpload: function (file) {
      let size_M = file.size / 1024 /1024; //多少M
      let imageType = file.type.trim();
      let limit2M = size_M > 2 ? false : true
      if(!limit2M){
        this.$message("上传文件不能超过2M");
      }
      let valid_image_type = true;
      if(imageType == "image/png" || imageType == "image/jpeg"){
        valid_image_type = true;
      } else{
        valid_image_type = false;
        this.$message({
          type:"warning",
          message: "上传文件的图片格式不正确！",
      })
      }
      return limit2M && valid_image_type;
    },
  },
};
</script>
<style lang="less" scoped>
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
  border: 1px solid #ddd;
}
</style>
